<template>
  <div class="staffManage-container" style="padding: 20px">

    <el-form
      ref="ruleForm"
      :model="ruleForm"
      :rules="rules"
      label-width="100px"
      class="demo-ruleForm"
      :label-position="labelPosition"
    >
      <h1>STEP1.填写基本信息</h1>
      <div class="step-common">
        <el-form-item label="员工姓名" prop="staffName">
          <el-input v-model="ruleForm.staffName" placeholder="请填写真实姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="ruleForm.sex" placeholder="请选择性别">
            <el-option label="男" value="0" />
            <el-option label="女" value="1" />
            <el-option label="未知" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="生日" required>
          <el-col :span="11">
            <el-form-item prop="birthday">
              <el-date-picker
                v-model="ruleForm.birthday"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                :picker-options="expireTimeOption"
              />
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="ruleForm.mobile" onkeyup="value=value.replace(/[^\d]/g,'')" placeholder="输入电话号码" />
        </el-form-item>
        <el-collapse v-model="activeNames">
          <el-collapse-item title="完善更多资料" name="1">
            <el-form-item label="国籍" prop="country">
              <el-select
                v-model="ruleForm.country"
                filterable
                clearable
                placeholder="请选择国籍"
              >
                <el-option
                  v-for="item in countryList"
                  :key="item.dictValue"
                  :label="item.dictList"
                  :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="籍贯" prop="nativePlace">
              <el-select
                v-model="ruleForm.nativePlace"
                filterable
                clearable
                placeholder="请选择籍贯"
              >
                <el-option
                  v-for="item in nativePlaceList"
                  :key="item.dictValue"
                  :label="item.dictList"
                  :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="民族" prop="nation">
              <el-select
                v-model="ruleForm.nation"
                filterable
                clearable
                placeholder="请选择民族"
              >
                <el-option
                  v-for="item in nationList"
                  :key="item.dictValue"
                  :label="item.dictList"
                  :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="党派" prop="clan">
              <el-select
                v-model="ruleForm.clan"
                filterable
                clearable
                placeholder="请选择党派"
              >
                <el-option
                  v-for="item in clanList"
                  :key="item.dictValue"
                  :label="item.dictList"
                  :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="学历" prop="diploma">
              <el-select
                v-model="ruleForm.diploma"
                filterable
                clearable
                placeholder="请选择学历"
              >
                <el-option
                  v-for="item in diplomaList"
                  :key="item.dictValue"
                  :label="item.dictList"
                  :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="婚姻状态" prop="maritalStatus">
              <el-select
                v-model="ruleForm.maritalStatus"
                filterable
                clearable
                placeholder="请选择婚姻状态"
              >
                <el-option
                  v-for="item in maritalStatusList"
                  :key="item.dictValue"
                  :label="item.dictList"
                  :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="证件类型" prop="idType">
              <el-select
                v-model="ruleForm.idType"
                filterable
                clearable
                placeholder="请选择证件类型"
              >
                <el-option
                  v-for="item in idTypeList"
                  :key="item.dictValue"
                  :label="item.dictList"
                  :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="证件号码" prop="idCard">
              <el-input v-model="ruleForm.idCard" placeholder="输入证件号码" />
            </el-form-item>
            <el-form-item label="家庭电话" prop="familyPhone">
              <el-input v-model="ruleForm.familyPhone" placeholder="输入家庭电话" />
            </el-form-item>
            <el-form-item label="电子邮箱" prop="email">
              <el-input v-model="ruleForm.email" placeholder="输入电子邮箱" />
            </el-form-item>
            <el-form-item label="地址" prop="address">
              <el-input v-model="ruleForm.address" placeholder="输入地址" />
            </el-form-item>
            <el-form-item label="备注" prop="userDesc">
              <el-input
                v-model="ruleForm.userDesc"
                type="textarea"
                :rows="2"
                placeholder="备注描述，请控制在200字以内"
                maxlength="200"
              />
            </el-form-item>
          </el-collapse-item>
        </el-collapse>
      </div>

      <h1>STEP2.选择一个角色</h1>
      <div class="step-common">
        <el-form-item label="企业" required prop="k_EntId">
          <el-select
            v-model="ruleForm.entName"
            filterable
            clearable
            placeholder="请选择企业"
            @change="changeEnt"
          >
            <el-option
              v-for="lo in entNameList"
              :key="lo.k_EntId"
              :label="lo.entName"
              :value="lo.k_EntId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="机构" required prop="k_OrgId">
          <el-select
            v-model="ruleForm.orgName"
            filterable
            clearable
            placeholder="请选择机构"
            @change="changeOrg"
          >
            <el-option
              v-for="item in orgNameList"
              :key="item.k_OrgId"
              :label="item.orgName"
              :value="item.k_OrgId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-checkbox-group v-model="ruleForm.role">
            <el-checkbox v-for="item in roleList" :key="item.roleName" :label="item.k_RoleCode">{{ item.roleName }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </div>

      <h1>STEP3.登录账号</h1>
      <div class="step-common">
        <el-form-item label="登录名" prop="k_LgnName">
          <el-input v-model="ruleForm.k_LgnName" placeholder="请输入该常用手机号作为登录账号" />
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input v-model="ruleForm.code" placeholder="请输入验证码" />
          <el-button type="primary" :disabled="isDisabled" @click="sendMsg">{{ buttonName }}</el-button>
        </el-form-item>

      </div>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">保存草稿</el-button>
        <el-button type="primary" @click="submitStaffDetail('ruleForm')">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getEntDoc, getOrgDoc, getStaffDetail, getRoleDoc, getDict, saveStaffDetail, updateStaffDetail, submitStaffDetail, sendVerificationCode } from '@/api/bill'
export default {
  data() {
    const isMobile = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('手机号不可为空'))
      } else {
        if (value !== '') {
          const reg = /^1[3456789]\d{9}$/
          if (!reg.test(value)) {
            callback(new Error('请输入有效的手机号码'))
          }
        }
        callback()
      }
    }
    return {
      expireTimeOption: {
        disabledDate(date) {
          // disabledDate 文档上：设置禁用状态，参数为当前日期，要求返回 Boolean
          return date.getTime() > Date.now() - 24 * 60 * 60 * 1000
        }
      },
      buttonName: '发送短信',
      isDisabled: false,
      time: 60,
      countryList: [],
      nativePlaceList: [],
      nationList: [],
      clanList: [],
      diplomaList: [],
      maritalStatusList: [],
      idTypeList: [],
      activeNames: [],
      labelPosition: 'left',
      entNameList: [],
      orgNameList: [],
      loading: false,
      // billNo : this.$route.params.billNo || '',
      roleList: [],
      isNewUser: false,
      ruleForm: {
        checked: {},
        billNo: this.$route.params.billNo,
        staffName: '',
        sex: '',
        birthday: '',
        mobile: '',
        k_EntId: '',
        entName: '',
        k_OrgId: '',
        orgName: '',
        role: [],
        roleList: [],
        k_LgnName: '',
        country: '',
        nativePlace: '',
        nation: '',
        clan: '',
        diploma: '',
        maritalStatus: '',
        idType: '',
        idCard: '',
        familyPhone: '',
        email: '',
        address: '',
        code: '',
        codetype: 'ADD_STAFF',
        userDesc: ''
      },
      rules: {
        // familyPhone:[
        //     {required : false},
        //     {min: 1, max: 32, message: '长度在 1 到 32 个字符', trigger: 'blur' }
        // ],
        // idCard :[
        //     {required : false},
        //     {validator: isCardId, trigger: 'blur' }
        // ],
        staffName: [
          { required: true, message: '请输入职员名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 32 个字符', trigger: 'blur' }
        ],
        sex: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        birthday: [
          { required: true, message: '请选择生日', trigger: 'change' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: isMobile, trigger: 'blur' }
        ],
        k_EntId: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        k_OrgId: [
          { required: true, message: '请选择机构', trigger: 'change' }
        ],
        role: [
          { type: 'array', required: true, message: '请至少选择一个角色', trigger: 'change' }
        ],
        k_LgnName: [
          { required: true, message: '请输入登录名', trigger: 'blur' },
          { min: 1, max: 30, message: '长度在 1 到 40 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getEntDoc()
    this.getStaffDetail()
    this.getDict('Country')
    this.getDict('NativePlace')
    this.getDict('Nation')
    this.getDict('Clan')
    this.getDict('Diploma')
    this.getDict('MaritalStatus')
    this.getDict('IdType')
  },
  methods: {
    sendMsg() {
      if (this.ruleForm.k_LgnName.length === 0) {
        this.$message({
          type: 'warning',
          message: '请输入手机号码'
        })
      } else {
        const me = this
        me.isDisabled = true
        const interval = window.setInterval(function() {
          me.buttonName = '（' + me.time + '秒）后重新发送'
          --me.time
          if (me.time < 0) {
            me.buttonName = '重新发送'
            me.time = 60
            me.isDisabled = false
            window.clearInterval(interval)
          }
        }, 1000)
        this.sendVerificationCode()
      }
    },
    sendVerificationCode() {
      const params = {
        phoneNo: this.ruleForm.k_LgnName,
        type: 'CHANGE_ERP_ACCOUNT'
      }
      sendVerificationCode(params).then(res => {

      })
        .finally(() => {
          this.loading = false
        })
    },
    changeEnt(val) {
      this.ruleForm.k_OrgId = ''
      this.ruleForm.orgName = ''
      let obj = {}
      obj = this.entNameList.find((item) => {
        return item.k_EntId === val
      })
      if (obj != null) {
        this.ruleForm.entName = obj.entName
        this.ruleForm.k_EntId = obj.k_EntId
      } else {
        this.ruleForm.entName = ''
        this.ruleForm.k_EntId = ''
      }
      this.getOrgDoc()
    },
    changeOrg(val) {
      let obj = {}
      obj = this.orgNameList.find((item) => {
        return item.k_OrgId === val
      })
      if (obj !== null) {
        this.ruleForm.orgName = obj.orgName
        this.ruleForm.k_OrgId = obj.k_OrgId
      } else {
        this.ruleForm.orgName = ''
        this.ruleForm.k_OrgId = ''
      }
      this.getRoleDoc()
    },
    getDict(val) {
      const params = {
        fdName: val
      }
      getDict(params).then(res => {
        if (val === 'Country') {
          this.countryList = res.data
        } else if (val === 'NativePlace') {
          this.nativePlaceList = res.data
        } else if (val === 'Nation') {
          this.nationList = res.data
        } else if (val === 'Clan') {
          this.clanList = res.data
        } else if (val === 'Diploma') {
          this.diplomaList = res.data
        } else if (val === 'MaritalStatus') {
          this.maritalStatusList = res.data
        } else if (val === 'IdType') {
          this.idTypeList = res.data
        }
      })
        .finally(() => {
          this.loading = false
        })
    },
    getRoleDoc() {
      const params = {
        requestEntId: this.ruleForm.k_EntId,
        requestOrgId: this.ruleForm.k_OrgId
      }
      getRoleDoc(params).then(res => {
        this.roleList = res.data
      })
        .finally(() => {
          this.loading = false
        })
    },
    getEntDoc() {
      const params = {
      }
      getEntDoc(params).then(res => {
        this.entNameList = res.data
      })
        .finally(() => {
          this.loading = false
        })
    },
    getOrgDoc() {
      const params = {
        requestEntId: this.ruleForm.k_EntId
      }
      getOrgDoc(params).then(res => {
        this.orgNameList = res.data
      })
        .finally(() => {
          this.loading = false
        })
    },
    getStaffDetail() {
      const params = {
        billNo: this.ruleForm.billNo
      }
      if (typeof (this.ruleForm.billNo) !== 'undefined') {
        if (this.ruleForm.billNo.length !== 0) {
          getStaffDetail(params).then(res => {
            this.ruleForm = res.data
            this.roleList = res.data.roleList
            this.getOrgDoc()
          })
            .finally(() => {
              this.loading = false
            })
        }
      }
    },
    open(val) {
      let sex = ''
      if (this.ruleForm.sex === '0') {
        sex = '男'
      } else if (this.ruleForm.sex === '1') {
        sex = '女'
      } else {
        sex = '未知'
      }
      const arr = []
      const value = '姓名：' + this.ruleForm.staffName + '&emsp;&emsp;&emsp;性别：' + sex
      const value2 = '出生年月：' + this.ruleForm.birthday + '&emsp;&emsp;&emsp;联系方式：' + this.ruleForm.mobile
      arr[0] = value
      arr[1] = value2
      arr[2] = ''
      for (let i = 0; i < this.ruleForm.role.length; i++) {
        const role = this.ruleForm.role[i]
        let roleName = ''
        this.roleList.forEach(value1 => {
          if (role === value1.k_RoleCode) {
            roleName = value1.roleName
          }
        })
        arr[(1 + i + 2)] = '角色' + (i + 1) + '：' + this.ruleForm.entName + '-' + this.ruleForm.orgName + '-' + roleName
      }
      const pw = val.data.newUser ? '1' : '原账号密码'
      arr[(this.ruleForm.role.length + 4)] = '绑定账号登录名：' + this.ruleForm.k_LgnName + '&emsp;&emsp;&emsp;初次登录密码：' + pw
      const str = arr.join('<br/>')
      this.$alert(str, '创建成功', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确定',
        callback: action => {
          this.$message({
            type: 'success',
            message: val.message,
            showClose: true
          })
        }
      })
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.ruleForm.billNo.length !== 0) {
            updateStaffDetail({
              ...this.ruleForm
            }).then(res => {
              if (res.code === '40001') {
                this.$message({
                  type: 'success',
                  message: res.message,
                  showClose: true
                })
              } else {
                this.$message({
                  type: 'error',
                  message: res.message,
                  showClose: true
                })
              }
            })
          } else {
            saveStaffDetail({
              ...this.ruleForm
            }).then(res => {
              if (res.code === '40001') {
                this.ruleForm.billNo = res.data.billNo
                this.$message({
                  type: 'success',
                  message: res.message,
                  showClose: true
                })
              } else {
                this.$message({
                  type: 'error',
                  message: res.message,
                  showClose: true
                })
              }
            })
          }
        } else {
          return false
        }
      })
    },
    submitStaffDetail(formName) {
      this.ruleForm.codetype = 'ADD_STAFF'
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // console.log(this.ruleForm);
          submitStaffDetail({
            ...this.ruleForm
          }).then(res => {
            if (res.code === '40001') {
              this.ruleForm.billNo = res.data.billNo
              this.open(res)
              // this.$message({
              //     type: 'success',
              //     message: res.message,
              //     showClose: true
              // })
            } else {
              this.$message({
                type: 'error',
                message: res.message,
                showClose: true
              })
            }
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  h1{
    color: #20a0ff;
    font-size: 18px;
  }
  .el-input, .el-select ,.el-date-picker{
    width: 250px;
  }
  .staffManage{
    &-container{
      .el-input{
        width: 250px;
      }
      .step-common{
        padding: 20px;
      }
    }
  }
</style>
